package com.aos.erp.schools.service.sys.impl;

import com.aos.erp.common.bean.IPageBean;
import com.aos.erp.common.bean.ResultBean;
import com.aos.erp.common.bean.ResultEntity;
import com.aos.erp.common.constant.GlobalConstant;
import com.aos.erp.common.dao.mapper.Condition;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.schools.enums.student.sys.UserStatus;
import com.aos.erp.schools.enums.student.sys.UserType;
import com.aos.erp.schools.mapper.sys.DepartmentMapper;
import com.aos.erp.schools.mapper.sys.DepartmentUserMapper;
import com.aos.erp.schools.mapper.sys.PositionUserMapper;
import com.aos.erp.schools.mapper.sys.UserMapper;
import com.aos.erp.schools.model.sys.*;
import com.aos.erp.schools.model.sys.dto.UserDto;
import com.aos.erp.schools.model.sys.vo.UserVo;
import com.aos.erp.schools.remote.model.SynUser;
import com.aos.erp.schools.remote.sys.SynUserService;
import com.aos.erp.schools.service.mq.SendMessageService;
import com.aos.erp.schools.service.sys.UserService;
import com.aos.erp.schools.util.CookieUtils;
import com.aos.erp.schools.util.PasswordUtils;
import com.aos.erp.schools.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private DepartmentUserMapper departmentUserMapper;
    @Resource
    private PositionUserMapper positionUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SendMessageService sendMessageService;
    @Resource
    SynUserService synUserService;

    @Override
    public Map<String, Object> addBean(UserVo userVo, String appCode) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("depCode", userVo.getDepCode());
        Department dep = departmentMapper.findByParams(params);
        if (dep == null) {
            throw new BizException("部门组织code错误");
        }
        Condition condition = new Condition(User.class);
        condition.eqFiled("username", userVo.getUsername());
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user != null) {
            throw new BizException("账号已存在");
        }

        //用户
        user = new User();
        BeanUtils.copyProperties(userVo, user);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        user.setState(Integer.valueOf(UserStatus.normal.getValue().toString()));
        String slat = PasswordUtils.getSalt();
        String password = PasswordUtils.createPassWord(8);
        //String ciphertext = PasswordUtils.getSaltMD5(password,slat);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setSalt(slat);
        user.setType(Integer.valueOf(UserType.school.getValue().toString()));
        userMapper.insertObject(user);
        Long userId = user.getId();
        //用户部门
        DepartmentUser departmentUser = new DepartmentUser();
        departmentUser.setDepId(dep.getId());
        departmentUser.setUserId(userId);
        departmentUserMapper.insert(departmentUser);
        //用户岗位
        PositionUser positionUser = new PositionUser();
        positionUser.setPositionId(userVo.getPositionId());
        positionUser.setUserId(userId);
        positionUserMapper.insert(positionUser);

        //TODO 同步用户
        sendMessageService.synUserInfo(synUser(user, appCode, dep.getDepCode()));

        Map<String, Object> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("password", password);
        return map;
    }

    public SynUser synUser(User user, String appCode, String depCode) throws BizException {
        SynUser synUser = new SynUser();
        BeanUtils.copyProperties(user, synUser);
        synUser.setAppCode(appCode);
        List orgCodeList = new ArrayList();
        orgCodeList.add(depCode);
        synUser.setOrgCodeList(orgCodeList);
        return synUser;
    }

    @Override
    public User findByName(String name) {
        List<User> list = userMapper.findByName(name);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response, String username, String password,
                                     String code, String captchaCode, String appCode) throws BizException {
        //TODO
        /*String captchaValue =  redisTemplate.opsForValue().get(captchaCode);
        if (captchaValue == null){
            throw new BizException("验证码失效");
        }
        if (captchaValue.equals(code)){
            redisTemplate.delete(captchaCode);
        }else{
            throw new BizException("验证码错误");
        }*/

        Condition condition = new Condition(User.class);
        condition.eqFiled("username", username);
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user == null) {
            throw new BizException("账号不存在");
        }
        //只能驾校用户才能登录驾校系统
        if (!user.getType().equals(UserType.school.getValue())) {
            throw new BizException("账号不存在");
        }
        if (user.getState().equals(UserStatus.del.getValue())) {
            throw new BizException("账号已被删除");
        }
        if (user.getState().equals(UserStatus.disable.getValue())) {
            throw new BizException("账号已被禁用");
        }
        /*String ciphertext =  PasswordUtils.getSaltMD5(password,user.getSalt());
        if(!user.getPassword().equals(ciphertext)){
            throw new BizException("密码错误");
        }
        CookieUtils.setCookie(request,response,GlobalConstant.cookieName,user.getId().toString(),GlobalConstant.cookieMaxAge,"UTF-8");*/
        //TODO 同步用户登录
        ResultBean o = synUserService.userLogin(appCode, username, password);
        if (ResultBean.CODE_FAIL == o.getCode()) {
            throw new BizException(o.getErrMsg());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("data", o.getData());
        return map;
    }

    /**
     * 退出登录
     *
     * @param token 登录用户token
     */
    public void logout(String token) throws BizException {
        ResultBean o = synUserService.userLoginOut(token);
        if (ResultBean.CODE_FAIL == o.getCode()) {
            throw new BizException(o.getErrMsg());
        }
    }

    /**
     * 分页查询
     *
     * @param pageIndex 当前页码
     * @param pageSize  每页显示条数
     * @param name      部门组织code
     * @param name      用户姓名
     * @param username  用户账号
     * @param depName   部门名称
     * @return
     */
    @Override
    public IPage<UserDto> queryByPage(Integer pageIndex, Integer pageSize, String depCode, String name, String username, String depName) {
        Page<UserDto> pageBean = new Page<UserDto>(pageIndex, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("depCode", depCode);
        map.put("name", name);
        map.put("username", username);
        map.put("depName", depName);
        map.put("state", UserStatus.normal.getValue());
        map.put("pageBean", pageBean);
        List<UserDto> list = baseMapper.findByParams(map);
        IPage<UserDto> page = pageBean;
        page.setRecords(list);
        return page;
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    public int isDel(String id, String appCode) throws Exception {
        try {
            User user = new User();
            user.setId(Long.valueOf(id));
            user.setState(Integer.valueOf(UserStatus.del.getValue().toString()));
            user.setUpdated(new Date());
            int i = baseMapper.updateObject(user);

            //TODO 同步用户删除
            SynUser synUser = new SynUser();
            synUser.setAppCode(appCode);
            synUser.setUsername(user.getUsername());
            sendMessageService.deleteUser(synUser);

            return i;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 修改用户
     *
     * @param userVo
     * @return
     * @throws Exception
     */
    public int updateObject(UserVo userVo) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("depCode", userVo.getDepCode());
        Department dep = departmentMapper.findByParams(params);
        if (dep == null) {
            throw new BizException("部门组织code错误");
        }
        User user = new User();
        user.setUpdated(new Date());
        user.setId(Long.valueOf(userVo.getId()));
        BeanUtils.copyProperties(userVo, user);
        //用户部门
        Condition condition = new Condition(DepartmentUser.class);
        condition.eqColumn("user_id", userVo.getId());
        DepartmentUser departmentUser = departmentUserMapper.selectOneBean(condition.getWrapper());
        if (!dep.getId().equals(departmentUser.getDepId())) {
            departmentUser.setDepId(dep.getId());
            departmentUserMapper.updateById(departmentUser);
        }
        //用户岗位
        condition = new Condition(PositionUser.class);
        condition.eqColumn("user_id", userVo.getId());
        PositionUser positionUser = positionUserMapper.selectOneBean(condition.getWrapper());
        if (!userVo.getPositionId().equals(positionUser.getPositionId())) {
            positionUser.setPositionId(userVo.getPositionId());
            positionUserMapper.updateById(positionUser);
        }
        //用户
        int i = baseMapper.updateObject(user);
        return i;
    }

    /**
     * 根据用户id查询
     *
     * @param id
     * @return
     */
    public UserDto findById(Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<UserDto> list = baseMapper.findByParams(params);
        if (list == null || list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    public User createNewUser(String name, String phone, String profilePhoto) {
        User bean = new User();
        bean.setName(name);
        baseMapper.insert(bean);
        return bean;
    }

    @Override
    public IPageBean<User> findByPage(IPageBean<User> page) {
        return baseMapper.selectPage(page, baseMapper.createQuery());
    }

    @Override
    public IPageBean<User> findByPage(long page, long size, QueryWrapper<User> qw) {
        return null;
    }

    @Override
    public IPageBean<User> findByPage(long page, long size, String name, String phone) {
        return null;
    }

    @Override
    public IPageBean<User> findByPage(long page, long size, String name, String phone, Date startTime, Date endTime) {
        return null;
    }

    public User getById(long id) {
        return baseMapper.selectById(id);
    }

    public void update(User userInfo) {
        baseMapper.updateById(userInfo);
    }

    @Override
    public void updateInfo(long id, String name, String profilePhoto) {
        User userInfo = baseMapper.selectById(id);
        if (StringUtils.isNotBlank(name)) {
            userInfo.setName(name);
        }
        baseMapper.updateById(userInfo);
    }

    public User updatePhone(long id, String phone) {
        User userInfo = baseMapper.selectById(id);
        if (StringUtils.isNotBlank(phone)) {
            userInfo.setMobile(phone);
        }
        baseMapper.updateById(userInfo);
        return userInfo;
    }

    public int changePassword(String username, String password, String oldpassword, String currentUserId, String appCode) throws Exception {
        if (StringUtils.isEmpty(currentUserId)) {
            throw new BizException("请重新登录");
        }
        Condition condition = new Condition(User.class);
        condition.eqFiled("username", username);
        User user = baseMapper.selectOne(condition.getWrapper());
        if (user == null) {
            throw new BizException("账号不存在");
        }
        String oldpwd = PasswordUtils.getSaltMD5(oldpassword, user.getSalt());
        if (!oldpwd.equals(user.getPassword())) {
            throw new BizException("旧密码错误");
        }

        user.setUpdated(new Date());
        user.setState(Integer.valueOf(UserStatus.normal.getValue().toString()));
        String slat = PasswordUtils.getSalt();
        //String ciphertext = PasswordUtils.getSaltMD5(password,slat);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setSalt(slat);
        //TODO 同步用户
        sendMessageService.synUserInfo(synUser(user, appCode, UserUtil.getUserDepCode(currentUserId)));
        return baseMapper.updateObject(user);
    }
}
